<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick } from 'vue'
import { addIngredients, getIngredientsList, updateIngredients, deleteIngredients } from '@/api/ingredients'
import { getDictList } from '@/api/dict'
import type { IngredientsSearchParam, Ingredients } from '@/api/ingredients/types'
import type { Page } from '@/api/common/types'
import type { Dict } from '@/api/dict/types'
import { ElForm, ElMessage, ElMessageBox, type FormRules, type UploadProps, type UploadUserFile } from 'element-plus'
import { useTokenStore } from '@/stores/tokenStore'

const tokenStore = useTokenStore()
const base_url = import.meta.env.VITE_APP_BASE_API
const dictList = ref<Dict[]>([])

const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
const ingredientsList = ref<Ingredients[]>([])
const queryFormRef = ref()
const queryForm = reactive<IngredientsSearchParam>({
    name: '',
    type: ''
})
const title = ref('添加食材')
const ingredientsFormVisible = ref(false)
const ingredientsFormRef = ref()
const ingredientsForm = ref<Ingredients>({
    name: '',
    type: '',
    url: '',
    description: ''
})
/* 表单验证 */
const ingredientsFormRules = ref<FormRules>({
    name: [{ required: true, message: '请输入食材名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择食材类型', trigger: 'blur' }],
    url: [{ required: true, message: '请上传食材图片', trigger: 'blur' }],
    description: [{ required: true, message: '请输入食材描述', trigger: 'blur' }]
})
/* 获取字典数据 */
const listData = () => {
    getDictList('ingredients').then(resp => {
        dictList.value = resp
    }).catch(e => {
        ElMessage.error(e.message)
    })
}
/* 获取食材列表 */
const listIngredients = (pager = 1) => {
    pageNum.value = pager
    getIngredientsList(pageNum.value, pageSize.value, queryForm).then(resp => {
        ingredientsList.value = resp.rows
        total.value = resp.total
    }).catch(e => {
        ElMessage.error(e.message)
    })
}
/* 新增食材 */
const handleAdd = () => {
    ingredientsFormVisible.value = true
    title.value = '新增食材'
    nextTick(() => {
        ingredientsForm.value = {
            name: '',
            type: '',
            url: '',
            description: ''
        }
        fileList.value = []
        ingredientsFormRef.value.resetFields()
    })
}
/* 上传食材图片 */
const fileList = ref<UploadUserFile[]>([])
/* 上传食材图片前 */
const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt1MB = file.size / 1024 / 1024 < 1
    if (!isJPG && !isPNG) {
        ElMessage.error('上传图片格式错误')
        return false
    }
    if (!isLt1MB) {
        ElMessage.error('上传图片大小不能超过 1MB')
        return false
    }
}
/* 上传食材图片成功后 */
const handleOnSuccess: UploadProps['onSuccess'] = (resp, file, files) => {
    ingredientsForm.value.url = resp.data
    // 上传成功后,重新校验
    ingredientsFormRef.value.validateField('url')
}
/* 图片删除时执行 */
const handleOnRemove: UploadProps['onRemove'] = (file, files) => {
    ingredientsForm.value.url = ''
    fileList.value = []
    // 删除后,重新校验
    ingredientsFormRef.value.validateField('url')
}
/* 图片超出个数 */
const fileLimit = ref(1)
const handleOnExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(`当前限制上传${fileLimit.value}张图片`)
}
/* 
    新增食材 
    更新表单数据
*/
const confirm = () => {
    ingredientsFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            if (!ingredientsForm.value.id) {
                await addIngredients(ingredientsForm.value)
                pageNum.value = 1
            } else {
                await updateIngredients(ingredientsForm.value)
            }
            ingredientsFormVisible.value = false
            ElMessage.success('操作成功')
            setTimeout(() => {
                listIngredients()
            }, 500)
        }
    })
}
/* 编辑食材 */
const handleEdit = (row: Ingredients) => {
    ingredientsFormVisible.value = true
    title.value = '羞羞食材信息'
    nextTick(() => {
        ingredientsForm.value = { ...row }
        fileList.value = [{
            name: row.name,
            url: base_url + row.url
        }]
        ingredientsFormRef.value.clearValidate()
    })
}

/* 删除食材 */
const handleDelete = (id: number) => {
    ElMessageBox.confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        await deleteIngredients(id)
        ElMessage.success('删除成功')
        setTimeout(() => {
            listIngredients()
        }, 500)
    }).catch(() => {
        ElMessage.info('取消删除');
    });
}

/* 重置表单 */
const resetForm = () => {
    queryFormRef.value.resetFields()
    listIngredients()
}

onMounted(() => {
    listData()
    listIngredients()
})

</script>

<template>
    <!-- {{ dictList }} -->
    <!-- {{ ingredientsList }} -->
    <div class="app-container">
        <el-dialog :title="title" v-model="ingredientsFormVisible" :close-on-click-modal="false">
            <el-form :model="ingredientsForm" :rules="ingredientsFormRules" ref="ingredientsFormRef" label-width="80px">
                <el-form-item label="食材名称" prop="name">
                    <el-input v-model="ingredientsForm.name" placeholder="请输入食材名称" />
                </el-form-item>
                <el-form-item label="食材图片" prop="url">
                    <el-upload :action="base_url + '/dishes-service/upload/image'" list-type="picture"                                                                                                                                                                                                       
                        :file-list="fileList" :before-upload="handleBeforeUpload" :on-success="handleOnSuccess"
                        :on-remove="handleOnRemove" :on-exceed="handleOnExceed" :limit="fileLimit">
                        <el-button size="small" type="primary" plain icon="Plus">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 500kb</div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="食材类型" prop="type">
                    <el-radio-group v-model="ingredientsForm.type">
                        <el-radio v-for="item in dictList" :key="item.value" :label="item.value" :value="item.value">{{
                            item.label
                        }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="食材描述" prop="description">
                    <el-input v-model="ingredientsForm.description" placeholder="请输入食材描述" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="ingredientsFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirm">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-form :model="queryForm" ref="queryFormRef" label-width="100px" inline>
            <el-form-item label="食材名称" prop="name">
                <el-input v-model="queryForm.name" placeholder="请输入食材名称" />
            </el-form-item>
            <el-form-item label="食材类型" prop="type">
                <el-select v-model="queryForm.type" style="width: 180px" placeholder="请选择食材类型" clearable>
                    <el-option v-for="item in dictList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="listIngredients()" plain>查询</el-button>
                <el-button type="info" icon="Refresh" plain @click="resetForm">重置</el-button>
                <el-button type="success" icon="Plus" plain @click="handleAdd">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="ingredientsList" style="width: 100%" stripe>
            <el-table-column label="食材名称" prop="name" />
            <el-table-column label="食材类型" prop="type">
                <template #default="scope">
                    <el-tag>{{dictList.find(item => item.value === scope.row.type)?.label}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="食材图片" prop="url">
                <template #default="scope">
                    <el-image :src="base_url + scope.row.url" style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column label="食材描述" prop="description" />
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="primary" icon="Edit" plain size="small"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="Delete" plain size="small"
                        @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 20px;" :total="total" layout="total, prev, pager, next, jumper,sizes"
            :page-sizes="[3, 5, 7, 10]" v-model:current-page="pageNum" v-model:page-size="pageSize"
            @current-change="listIngredients" @size-change="listIngredients()" size="small" />
    </div>
</template>

<style scoped></style>